$(document).ready(function(){

    $("#register").click(function(e){
        var email = $("#email").val().trim();
        var password = $("#password").val().trim();
        var confirmPassword = $("#confirm_password").val().trim();

        if(email != "" && password != "" && confirmPassword != ""){
            if(isValidEmailAddress(email)){
                if(password == confirmPassword){
                    $("#reg_error").css("display", "none");
                    sendRegAjax(email, password, confirmPassword);
                }
                else{
                    $("#reg_error").text("Passwords are not the same!");
                    $("#reg_error").css("display", "block");
                }
            }
            else{
                $("#reg_error").text("Not an email!");
                $("#reg_error").css("display", "block");
            }
        }
        else{
            $("#reg_error").text("All fields must be filled!");
            $("#reg_error").css("display", "block");
        }
    });

    $("#reg_close").click(function(e){
        $("#wind").hide();
    });
});

function isValidEmailAddress(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
};

function sendRegAjax(e_mail, pass, confPass){
    $.ajax({
        accepts: "application/json",
        url: "/registration",
        type: 'POST',
        data: {email: e_mail, password: pass, confirmPassword: confPass},
        success: function(data) {
            var response = JSON.parse(data);
            if(response.successfulRegistration == true){
                showLoginForm();
            }
            else{
                $("#reg_error").text(response.regErrorAttribute);
                $("#reg_error").css("display", "block");
            }
        },
        error: function(error) {
            alert('Sorry, an error occured');
        }
    });
}

function showLoginForm(){
    $("#wind").fadeOut(1000);
    $("#login-wind").fadeIn(1000);
}